package com.winchain.chainbill.bill.biz.repurchase.rx;

import com.shell.bee.persistence.transaction.Transaction;
import com.shell.bee.persistence.transaction.TransactionUtil;
import com.shell.framework.command.ChainBase;
import com.shell.framework.command.CommandContext;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.winchain.chainbill.bill.base.po.CbRpur;
import com.winchain.chainbill.bill.biz.Bill;
import com.winchain.chainbill.bill.biz.repurchase.cmd.BillRpurRjCmd;
import com.winchain.chainbill.bill.biz.repurchase.cmd.BillRpurRjMsgCmd;
import com.winchain.chainbill.bill.biz.repurchase.vo.BillRpur;
import com.winchain.chainbill.bill.biz.send.cmd.BillMoveCmd;
import com.winchain.chainbill.bill.biz.send.cmd.BillOptCmd;
import com.winchain.chainbill.bill.biz.send.cmd.BillTimeoutCmd;
import com.winchain.chainbill.bill.biz.send.rx.BatchBillEvent;
import com.winchain.chainbill.bill.biz.send.vo.BatchBillStats;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillRpurRejectSubscriber extends OnErrorNotImplementedSubscriber<BatchBillEvent<BillRpur, CbRpur>> {
	@Autowired
	private BillTimeoutCmd<CbRpur> billTimeoutCmd;
	@Autowired
	private BillOptCmd<CbRpur> billOptCmd;
	@Autowired
	private BillRpurRjCmd billRpurRjCmd;
	@Autowired
	private BillRpurRjMsgCmd billRpurRjMsgCmd;
	@Autowired
	private BillMoveCmd<CbRpur> billMoveCmd;

	public void onApplicationEvent(final BatchBillEvent<BillRpur, CbRpur> t) {
		List<BillRpur> records = t.getRecs();
		BatchBillStats<CbRpur> stats = t.getStats();
		final Bill<CbRpur> source = new Bill();
		for (final BillRpur record : records) {
			try {
				TransactionUtil.execute(new Transaction() {
					public void doInTransaction() {
						source.setRec(record.getRec());
						source.setSource(record.getRpur());
						CommandContext<Bill<CbRpur>> context = new CommandContext();
						context.setSource(source);
						context.setValue("Operation", t.getOperation());
						context.setValue("TimeoutOperation", t.getTimeoutOpt());
						context.setValue("bizType", "cb_hld_pmt_rj");

						ChainBase<Bill<CbRpur>> crb = new ChainBase();
						crb.add(BillRpurRejectSubscriber.this.billTimeoutCmd);
						crb.add(BillRpurRejectSubscriber.this.billOptCmd);
						crb.add(BillRpurRejectSubscriber.this.billRpurRjCmd);
						crb.add(BillRpurRejectSubscriber.this.billMoveCmd);
						crb.add(BillRpurRejectSubscriber.this.billRpurRjMsgCmd);
						crb.execute(context);
					}
				}, new int[0]);

				stats.addPassedRecord(source);
			} catch (Exception e) {
				e.printStackTrace();
				stats.addAbnormalRecord(source);
				stats.addAbnormalMsg(e.getMessage());
			}
		}
	}
}
